//------------------------------------------------------------------------------
// The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at  http://www.nopCommerce.com/License.aspx. 
// 
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. 
// See the License for the specific language governing rights and limitations under the License.
// 
// The Original Code is nopCommerce.
// The Initial Developer of the Original Code is NopSolutions.
// All Rights Reserved.
// 
// Contributor(s): _______. 
//------------------------------------------------------------------------------

using System;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using NopSolutions.NopCommerce.BusinessLogic;
using NopSolutions.NopCommerce.BusinessLogic.Model;
using NopSolutions.NopCommerce.Common.Utils;
using NopSolutions.NopCommerce.BusinessLogic.Utils;

namespace NopSolutions.NopCommerce.Web.Modules
{
    public partial class CustomerRegisterControl : BaseNopFrontendUserControl
    {
        protected override void OnInit(EventArgs e) {
            //form fields
            phGender.Visible = this.CustomerService.FormFieldGenderEnabled;
            phDateOfBirth.Visible = this.CustomerService.FormFieldDateOfBirthEnabled;

            phCompanyName.Visible = this.CustomerService.FormFieldCompanyEnabled;
            rfvCompany.Enabled = this.CustomerService.FormFieldCompanyEnabled &&
                this.CustomerService.FormFieldCompanyRequired;
            //phVatNumber.Visible = this.TaxService.EUVatEnabled;
            phCompanyDetails.Visible = this.CustomerService.FormFieldCompanyEnabled;
            // || this.TaxService.EUVatEnabled;

            phStreetAddress.Visible = this.CustomerService.FormFieldStreetAddressEnabled;
            rfvStreetAddress.Enabled = this.CustomerService.FormFieldStreetAddressEnabled &&
                this.CustomerService.FormFieldStreetAddressRequired;
            phStreetAddress2.Visible = this.CustomerService.FormFieldStreetAddress2Enabled;
            rfvStreetAddress2.Enabled = this.CustomerService.FormFieldStreetAddress2Enabled &&
                this.CustomerService.FormFieldStreetAddress2Required;
            phPostCode.Visible = this.CustomerService.FormFieldPostCodeEnabled;
            rfvZipPostalCode.Enabled = this.CustomerService.FormFieldPostCodeEnabled &&
                this.CustomerService.FormFieldPostCodeRequired;
            phCity.Visible = this.CustomerService.FormFieldCityEnabled;
            rfvCity.Enabled = this.CustomerService.FormFieldCityEnabled &&
                this.CustomerService.FormFieldCityRequired;
            phCountry.Visible = this.CustomerService.FormFieldCountryEnabled;
            phStateProvince.Visible = this.CustomerService.FormFieldCountryEnabled &&
                this.CustomerService.FormFieldStateEnabled;
            phYourAddress.Visible = this.CustomerService.FormFieldStreetAddressEnabled ||
                this.CustomerService.FormFieldStreetAddress2Enabled ||
                this.CustomerService.FormFieldPostCodeEnabled ||
                this.CustomerService.FormFieldCityEnabled ||
                this.CustomerService.FormFieldCountryEnabled;

            phTelephoneNumber.Visible = this.CustomerService.FormFieldPhoneEnabled;
            rfvPhoneNumber.Enabled = this.CustomerService.FormFieldPhoneEnabled &&
                this.CustomerService.FormFieldPhoneRequired;
            phFaxNumber.Visible = this.CustomerService.FormFieldFaxEnabled;
            rfvFaxNumber.Enabled = this.CustomerService.FormFieldFaxEnabled &&
                this.CustomerService.FormFieldFaxRequired;
            phYourContactInformation.Visible = this.CustomerService.FormFieldPhoneEnabled ||
                this.CustomerService.FormFieldFaxEnabled;

            phNewsletter.Visible = this.CustomerService.FormFieldNewsletterEnabled;

            phTimeZone.Visible = DateTimeHelper.AllowCustomersToSetTimeZone && this.CustomerService.FormFieldTimeZoneEnabled;
            phPreferences.Visible = phTimeZone.Visible;

            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e) {
            this.ApplyLocalization();

            if (this.CustomerService.CustomerRegistrationType == CustomerRegistrationTypeEnum.Disabled) {
                pnlRegister.Visible = false;
                topicRegistrationNotAllowed.Visible = true;
            } else {
                pnlRegister.Visible = true;
                topicRegistrationNotAllowed.Visible = false;
            }

            if (!Page.IsPostBack) {
                if (NopContext.Current.User != null && !NopContext.Current.User.IsGuest) {
                    this.CustomerService.Logout();
                    Response.Redirect("~/register.aspx");
                }

                #region Username/emails hack
                phEmail.Visible = this.CustomerService.UsernamesEnabled;
                refUserNameOrEmail.Enabled = !this.CustomerService.UsernamesEnabled;
                #endregion

                this.FillCountryDropDowns();
                this.FillStateProvinceDropDowns();
                this.FillTimeZones();
                this.DataBind();
            }

            ctrlCaptcha.Visible = this.SettingManager.GetSettingValueBoolean("Common.RegisterCaptchaImageEnabled");
        }

        private void FillCountryDropDowns() {
            ddlCountry.Items.Clear();
            var countryCollection = this.CountryService.GetAllCountriesForRegistration();
            foreach (var country in countryCollection) {
                var ddlCountryItem2 = new ListItem(country.Name, country.CountryId.ToString());
                ddlCountry.Items.Add(ddlCountryItem2);
            }
        }

        protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e) {
            FillStateProvinceDropDowns();
        }

        private void FillStateProvinceDropDowns() {
            ddlStateProvince.Items.Clear();
            int countryId = 0;
            if (ddlCountry.SelectedItem != null)
                countryId = int.Parse(ddlCountry.SelectedItem.Value);

            var stateProvinceCollection = this.StateProvinceService.GetStateProvincesByCountryId(countryId);
            foreach (var stateProvince in stateProvinceCollection) {
                var ddlStateProviceItem2 = new ListItem(stateProvince.Name, stateProvince.StateProvinceId.ToString());
                ddlStateProvince.Items.Add(ddlStateProviceItem2);
            }
            if (stateProvinceCollection.Count == 0) {
                var ddlStateProvinceItem = new ListItem(GetLocaleResourceString("Address.StateProvinceNonUS"), "0");
                ddlStateProvince.Items.Add(ddlStateProvinceItem);
            }
        }

        private void FillTimeZones() {
            if (DateTimeHelper.AllowCustomersToSetTimeZone && this.CustomerService.FormFieldTimeZoneEnabled) {
                ddlTimeZone.Items.Clear();
                var timeZones = DateTimeHelper.GetSystemTimeZones();
                foreach (var timeZone in timeZones) {
                    string timeZoneName = timeZone.DisplayName;
                    var ddlTimeZoneItem2 = new ListItem(timeZoneName, timeZone.Id);
                    ddlTimeZone.Items.Add(ddlTimeZoneItem2);
                }
                CommonHelper.SelectListItem(ddlTimeZone, DateTimeHelper.CurrentTimeZone.Id);
            }
        }

        private void ApplyLocalization() {
            if (this.CustomerService.UsernamesEnabled) {
                EmailRequired.ErrorMessage = GetLocaleResourceString("Account.E-MailRequired");
                EmailRequired.ToolTip = GetLocaleResourceString("Account.E-MailRequired");
            }

            if (this.CustomerService.UsernamesEnabled) {
                revEmail.ErrorMessage = GetLocaleResourceString("Account.InvalidEmail");
                revEmail.ToolTip = GetLocaleResourceString("Account.InvalidEmail");
            }

            if (this.CustomerService.UsernamesEnabled) {
                lUsernameOrEmail.Text = GetLocaleResourceString("Account.Username");
            }

            if (this.CustomerService.UsernamesEnabled) {
                UserNameOrEmailRequired.ErrorMessage = GetLocaleResourceString("Account.UserNameRequired");
                UserNameOrEmailRequired.ToolTip = GetLocaleResourceString("Account.UserNameRequired");
            }

            if (!this.CustomerService.UsernamesEnabled) {
                refUserNameOrEmail.ErrorMessage = GetLocaleResourceString("Account.InvalidEmail");
                refUserNameOrEmail.ToolTip = GetLocaleResourceString("Account.InvalidEmail");
            }

            switch (this.CustomerService.CustomerRegistrationType) {
                case CustomerRegistrationTypeEnum.Standard: {
                        lblCompleteStep.Text = GetLocaleResourceString("Account.RegistrationCompleted");
                    }
                    break;
                case CustomerRegistrationTypeEnum.EmailValidation: {
                        lblCompleteStep.Text = GetLocaleResourceString("Account.ActivationEmailHasBeenSent");
                    }
                    break;
                case CustomerRegistrationTypeEnum.AdminApproval: {
                        lblCompleteStep.Text = GetLocaleResourceString("Account.AdminApprovalRequired");
                    }
                    break;
                case CustomerRegistrationTypeEnum.Disabled: {
                        lblCompleteStep.Text = "Registration method error";
                    }
                    break;
                default: {
                        lblCompleteStep.Text = "Registration method error";
                    }
                    break;
            }
        }

        protected void CreateUserError(object sender, EventArgs e) {
            if (this.SettingManager.GetSettingValueBoolean("Common.RegisterCaptchaImageEnabled")) {
                ctrlCaptcha.RegenerateCode();
            }
        }

        protected void btnRegister_Click(object sender, EventArgs e) {
            Page.Validate("CreateUserForm");
            if (!Page.IsValid) {
                pnlError.Visible = true;
            } else {
                if (this.SettingManager.GetSettingValueBoolean("Common.RegisterCaptchaImageEnabled")) {
                    if (!ctrlCaptcha.ValidateCaptcha()) {
                        ctrlCaptcha.RegenerateCode();
                        litError.Text = GetLocaleResourceString("Captcha.Incorrect");
                        pnlError.Visible = true;
                        return;
                    }
                }

                MembershipCreateStatus status = new MembershipCreateStatus();
                MembershipUser user = Membership.CreateUser(UserName.Text, Password.Text, Email.Text, null, null, true, out status);

                if (user == null) {
                    pnlError.Visible = true;

                    if (status == MembershipCreateStatus.DuplicateEmail)
                        litError.Text = GetLocaleResourceString("Account.DuplicateEmail");

                    if (status == MembershipCreateStatus.DuplicateUserName)
                        litError.Text = GetLocaleResourceString("Account.DuplicateUserName");
                } else {
                    Customer customer = null;
                    if (this.CustomerService.UsernamesEnabled) {
                        customer = this.CustomerService.GetCustomerByUsername(UserName.Text.Trim());
                    } else {
                        customer = this.CustomerService.GetCustomerByEmail(UserName.Text.Trim());
                    }
                    if (this.CustomerService.FormFieldGenderEnabled) {
                        if (rbGenderM.Checked)
                            customer.Gender = "M";
                        else
                            customer.Gender = "F";
                    }
                    customer.FirstName = txtFirstName.Text;
                    customer.LastName = txtLastName.Text;
                    if (this.CustomerService.FormFieldDateOfBirthEnabled) {
                        customer.DateOfBirth = dtDateOfBirth.SelectedDate;
                        this.CustomerService.UpdateCustomer(customer);
                    }
                    if (this.CustomerService.FormFieldCompanyEnabled) {
                        customer.Company = txtCompany.Text;
                    }
                    if (this.CustomerService.FormFieldStreetAddressEnabled) {
                        customer.StreetAddress = txtStreetAddress.Text;
                    }
                    //if (this.CustomerService.FormFieldStreetAddress2Enabled) {
                    //    customer.StreetAddress2 = txtStreetAddress2.Text;
                    //}
                    if (this.CustomerService.FormFieldPostCodeEnabled) {
                        customer.ZipPostalCode = txtZipPostalCode.Text;
                    }
                    if (this.CustomerService.FormFieldCityEnabled) {
                        customer.City = txtCity.Text;
                    }
                    if (this.CustomerService.FormFieldCountryEnabled) {
                        customer.CountryId = int.Parse(ddlCountry.SelectedItem.Value);
                    }
                    if (this.CustomerService.FormFieldCountryEnabled && this.CustomerService.FormFieldStateEnabled) {
                        customer.StateProvinceId = int.Parse(ddlStateProvince.SelectedItem.Value);
                    }
                    if (this.CustomerService.FormFieldPhoneEnabled) {
                        customer.PhoneNumber = txtPhoneNumber.Text;
                    }
                    if (this.CustomerService.FormFieldFaxEnabled) {
                        customer.FaxNumber = txtFaxNumber.Text;
                    }
                    if (this.CustomerService.FormFieldNewsletterEnabled) {
                        customer.ReceiveNewsletter = cbNewsletter.Checked;
                    }
                    if (DateTimeHelper.AllowCustomersToSetTimeZone && this.CustomerService.FormFieldTimeZoneEnabled) {
                        if (ddlTimeZone.SelectedItem != null && !String.IsNullOrEmpty(ddlTimeZone.SelectedItem.Value)) {
                            string timeZoneId = ddlTimeZone.SelectedItem.Value;
                            customer.TimeZoneId = DateTimeHelper.FindTimeZoneById(timeZoneId).Id;
                            this.CustomerService.UpdateCustomer(customer);
                        }
                    }

                    //set VAT number after country is saved
                    //if (this.TaxService.EUVatEnabled) {
                    //    string vatName = string.Empty;
                    //    string vatAddress = string.Empty;

                    //    customer.VatNumber = txtVatNumber.Text;
                    //    customer.VatNumberStatus = this.TaxService.GetVatNumberStatus(this.CountryService.GetCountryById(customer.CountryId),
                    //        customer.VatNumber, out vatName, out vatAddress);
                    //    //admin notification
                    //    if (!String.IsNullOrEmpty(customer.VatNumber) && this.TaxService.EUVatEmailAdminWhenNewVATSubmitted) {
                    //        this.MessageService.SendNewVATSubmittedStoreOwnerNotification(customer,
                    //            vatName, vatAddress, this.LocalizationManager.DefaultAdminLanguage.LanguageId);
                    //    }
                    //}

                    //billing address
                    var billingAddress = new Address() {
                        CustomerId = customer.CustomerId,
                        IsBillingAddress = true,
                        FirstName = customer.FirstName,
                        LastName = customer.LastName,
                        PhoneNumber = customer.PhoneNumber,
                        Email = customer.Email,
                        FaxNumber = customer.FaxNumber,
                        Company = customer.Company,
                        FullAddress = customer.StreetAddress,
                        City = customer.City,
                        StateProvinceId = customer.StateProvinceId,
                        ZipPostalCode = customer.ZipPostalCode,
                        CountryId = customer.CountryId,
                        CreatedOn = customer.RegistrationDate,
                        UpdatedOn = customer.RegistrationDate
                    };
                    if (this.CustomerService.CanUseAddressAsBillingAddress(billingAddress)) {
                        this.CustomerService.InsertAddress(billingAddress);

                        //set default billing address
                        customer.BillingAddressId = billingAddress.AddressId;
                        this.CustomerService.UpdateCustomer(customer);
                    }

                    //shipping address
                    var shippingAddress = new Address() {
                        CustomerId = customer.CustomerId,
                        IsBillingAddress = false,
                        FirstName = customer.FirstName,
                        LastName = customer.LastName,
                        PhoneNumber = customer.PhoneNumber,
                        Email = customer.Email,
                        FaxNumber = customer.FaxNumber,
                        Company = customer.Company,
                        FullAddress = customer.StreetAddress,
                        City = customer.City,
                        StateProvinceId = customer.StateProvinceId,
                        ZipPostalCode = customer.ZipPostalCode,
                        CountryId = customer.CountryId,
                        CreatedOn = customer.RegistrationDate,
                        UpdatedOn = customer.RegistrationDate
                    };
                    if (this.CustomerService.CanUseAddressAsShippingAddress(shippingAddress)) {
                        this.CustomerService.InsertAddress(shippingAddress);

                        //set default shipping address
                        customer.ShippingAddressId = shippingAddress.AddressId;
                        this.CustomerService.UpdateCustomer(customer);
                    }

                    //notification
                    if (this.CustomerService.NotifyNewCustomerRegistration) {
                        this.MessageService.SendNewCustomerNotificationMessage(customer, this.LocalizationManager.DefaultAdminLanguage.LanguageId);
                    }

                    // 
                    FormsAuthentication.SetAuthCookie(customer.Username, true);

                    pnlRegister.Visible = false;
                    pnlSuccess.Visible = true;
                }
            }
        }

        protected override void OnPreRender(EventArgs e) {
            lnkContinue.NavigateUrl = CommonHelper.GetStoreLocation();

            //return URL
            string returnUrl = CommonHelper.QueryString("ReturnUrl");
            if (!String.IsNullOrEmpty(returnUrl)) {
                lnkContinue.NavigateUrl = returnUrl;
            }

            base.OnPreRender(e);
        }
    }
}